<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="编号" v-model="listQuery.client_id">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button v-if="sys_client_add" class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加
      </el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 99%">
      <el-table-column align="center" label="编号">
        <template slot-scope="scope">
          <span>{{ scope.row.clientId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="密钥">
        <template slot-scope="scope">
          <span>{{ scope.row.clientSecret }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="应用名">
        <template slot-scope="scope">
          <span>
            <img v-if="scope.row.icon" class="user-avatar" style="width: 20px; height: 20px; border-radius: 50%;" :src="scope.row.icon+'?imageView2/1/w/20/h/20'">
            {{ scope.row. label}}
          </span>
        </template>
      </el-table-column>
      <el-table-column width="70px" align="center" label="域">
        <template slot-scope="scope">
          <span>{{ scope.row.scope}}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" label="授权模式">
        <template slot-scope="scope">
          <span>{{ scope.row.authorizedGrantTypes}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="访问地址">
        <template slot-scope="scope">
          <span>{{ scope.row.path}}</span>
        </template>
      </el-table-column>
      <el-table-column width="70px" align="center" label="序号">
        <template slot-scope="scope">
          <span>{{ scope.row.sort}}</span>
        </template>
      </el-table-column>



      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button v-if="sys_client_upd" size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="sys_client_del" size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="编号" prop="clientId">
          <el-input v-model="form.clientId" placeholder="编号" ></el-input>
        </el-form-item>
        <el-form-item label="密钥" prop="clientSecret">
          <el-input v-model="form.clientSecret" placeholder="密钥"></el-input>
        </el-form-item>

        <el-form-item label="应用名" prop="label">
          <el-input v-model="form.label" placeholder="应用名"></el-input>
        </el-form-item>
        <el-form-item label="域" prop="scope">
          <el-input v-model="form.scope" placeholder="域"></el-input>
        </el-form-item>
        <el-form-item label="授权模式" prop="authorizedGrantTypes">
          <el-input v-model="form.authorizedGrantTypes" placeholder="授权模式"></el-input>
        </el-form-item>
        <el-form-item label="访问地址" prop="path">
          <el-input v-model="form.path" placeholder="访问地址"></el-input>
        </el-form-item>
        <el-form-item label="序号" prop="sort">
          <el-input v-model="form.sort" placeholder="序号"></el-input>
        </el-form-item>
        <el-form-item label="选择放行" prop="autoapprove">、
          <el-radio v-model="form.autoapprove" label="0">否</el-radio>
          <el-radio v-model="form.autoapprove" label="1">是</el-radio>
        </el-form-item>

        <el-form-item label="图标">
              <my-upload field="file" @crop-upload-success="cropUploadSuccess" v-model="show" :width="200" :height="200" url="/admin/client/upload" :headers="headers" img-format="png"></my-upload>
              <img :src="form.icon">
              <el-button type="primary" @click="toggleShow" size="mini">设置图标
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj } from '@/api/client'
import waves from "@/directive/waves/index.js"; // 水波纹指令
import { mapGetters } from "vuex";
import { mapState } from "vuex";
import myUpload from "vue-image-crop-upload";
import { getToken } from "@/util/auth";
import ElFormItem from "element-ui/packages/form/src/form-item.vue"
import request from "@/router/axios";

export default {
  components: {
    ElFormItem,
    'my-upload': myUpload
  },
  name: "client",
  directives: {
    waves
  },
  data() {
    return {
      show: false,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      rules: {
        clientId: [
          {
            required: true,
            message: "编号",
            trigger: "blur"
          }
        ],
        clientSecret: [
          {
            required: true,
            message: "密钥",
            trigger: "blur"
          }
        ],
        label: [
          {
            required: true,
            message: "应用名",
            trigger: "blur"
          }
        ],
        scope: [
          {
            required: true,
            message: "域",
            trigger: "blur"
          }
        ],
        authorizedGrantTypes: [
          {
            required: true,
            message: "授权模式",
            trigger: "blur"
          }
        ],



      },
      form: {autoapprove:'0'},
      dialogFormVisible: false,
      dialogStatus: "",
      sys_client_add: false,
      sys_client_upd: false,
      sys_client_del: false,
      textMap: {
        update: "编辑",
        create: "创建"
      },
      tableKey: 0,
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "有效",
        1: "无效"
      };
      return statusMap[status];
    }
  },
  created() {
    this.getList();
    this.sys_client_add = this.permissions["sys_client_add"];
    this.sys_client_upd = this.permissions["sys_client_upd"];
    this.sys_client_del = this.permissions["sys_client_del"];
  },
  methods: {
     /**
     * upload success
     *
     * [param] jsonData   服务器返回数据，已进行json转码
     * [param] field
     */
    cropUploadSuccess(jsonData, field) {
      console.log("icon地址");
      console.log(jsonData.iconName);
      this.form.icon=jsonData.iconName;
    },
    toggleShow() {
      this.show = !this.show
    },
    getList() {
      this.listLoading = true;
      this.listQuery.orderByField = "create_time";
      this.listQuery.isAsc = false;
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleDelete(row) {
      delObj(row).then(response => {
        this.dialogFormVisible = false;
        this.getList();
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
      });
    },
    handleUpdate(row) {
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.form.clientId = row.clientId;
      this.form.clientSecret = row.clientSecret;
      this.form.label = row.label;
      this.form.scope = row.scope;
      this.form.authorizedGrantTypes = row.authorizedGrantTypes;
      this.form.icon = row.icon;
      this.form.autoapprove = row.autoapprove;
      this.form.path= row.path;
      this.form.sort= row.sort;
    },
    handleCreate() {
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.form.clientId = "";
      this.form.clientSecret = "";
      this.form.label = "";
      this.form.scope = "";
      this.form.authorizedGrantTypes = "";
      this.form.icon = "";
      this.form.autoapprove = "1";
      this.form.path= "";
      this.form.sort= "";
    },
    create(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      const set = this.$refs;
      set[formName].resetFields();
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;
          putObj(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
